package com.control.qct.businesssteward.activity;

import android.app.Dialog;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.control.qct.businesssteward.R;
import com.control.qct.businesssteward.adapter.MoreUserAdapter;
import com.control.qct.businesssteward.base.BaseActivity;
import com.control.qct.businesssteward.base.BaseBean;
import com.control.qct.businesssteward.httputils.FinalUrl;
import com.control.qct.businesssteward.httputils.HttpUtils;
import com.control.qct.businesssteward.model.LoginModel;
import com.control.qct.businesssteward.model.RecordUserInformationModel;
import com.control.qct.businesssteward.model.StoreModel;
import com.control.qct.businesssteward.utils.CustomCodeUtils;
import com.control.qct.businesssteward.utils.DialogUtil;
import com.control.qct.businesssteward.utils.EncodeUtils;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 登录
 * Created by Administrator on 2018/1/2 0002.
 */

public class LoginActivity extends BaseActivity {

    @BindView(R.id.et_enterprise_code)
    EditText mEtEnterpriseCode;//企业号
    @BindView(R.id.et_user)
    EditText mEtUser;//用户名
    @BindView(R.id.iv_more_user)
    ImageView mIvMoreUser;//选择更多已经登录过的用户名
    @BindView(R.id.et_password)
    EditText mEtPassword;//密码
    @BindView(R.id.iv_show_password)
    ImageView mIvShowPassword;//是否显示密码
    @BindView(R.id.cb_remember_password)
    CheckBox mCbRememberPassword;//是否记住密码
    @BindView(R.id.tv_login)
    TextView mTvLogin;//登录
    @BindView(R.id.tv_forget_password)
    TextView mTvForgetPassword;//忘记密码
    @BindView(R.id.rv_more_user)
    RecyclerView mRvMoreUser;
    @BindView(R.id.ll_bottom)
    LinearLayout mLlBottom;
    @BindView(R.id.iv_bg)
    ImageView mIvBg;
    @BindView(R.id.tv_test)
    TextView mTvTest;

    private boolean isShow;//显示隐藏密码
    private boolean isArrow;//上下拉图标切换
    private MoreUserAdapter mMoreUserAdapter;
    private List<RecordUserInformationModel> mMoreUserList = new ArrayList<>();
    private String mCompanyId;
    private String mLoginName;
    private String mLoginPassword;
    private Map<String, String> mParams;

    private final static int COUNTS = 10;//点击次数
    private final static long DURATION = 3 * 1000;//规定有效时间
    private long[] mHits = new long[COUNTS];//存储每个点击的时间戳
    private String[] URl_NAME = {"测试1", "正式"};
    private String[] URL_LIST = {"http://test.api.app.qcterp.com/", "http://api.app.qcterp.com/"};
    private Bundle mBundle;

    public LoginActivity() {
        super(R.layout.activity_login);
    }

    @Override
    protected void initView() {
        //相机授权
        CustomCodeUtils.setSelfPermission(this);
        mCbRememberPassword.setChecked(mSPUtils.getBoolean("remember_password"));
        if (mCbRememberPassword.isChecked()) {
            mEtEnterpriseCode.setText(new String(EncodeUtils.base64Decode(mSPUtils.getString("enterprise_code"))));
            mEtUser.setText(new String(EncodeUtils.base64Decode(mSPUtils.getString("user"))));
            mEtPassword.setText(new String(EncodeUtils.base64Decode(mSPUtils.getString("password"))));
        } else {//打包测试包时可以关闭
            mEtEnterpriseCode.setText(new String(EncodeUtils.base64Decode(mSPUtils.getString("enterprise_code"))));
            mEtUser.setText(new String(EncodeUtils.base64Decode(mSPUtils.getString("user"))));
        }
        getMoreUser();
    }

    @OnClick({R.id.iv_more_user, R.id.iv_show_password, R.id.tv_login, R.id.tv_forget_password})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_more_user://显示更多
                if (isArrow) {
                    isArrow = false;
                    mIvMoreUser.setImageResource(R.drawable.icon_denglu_xiaarrow);
                    mLlBottom.setVisibility(View.VISIBLE);
                    mRvMoreUser.setVisibility(View.GONE);
                } else {
                    isArrow = true;
                    mIvMoreUser.setImageResource(R.drawable.icon_denglu_shangarrow);
                    mLlBottom.setVisibility(View.GONE);
                    mRvMoreUser.setVisibility(View.VISIBLE);
                }
                break;
            case R.id.iv_show_password://是否显示密码
                if (isShow) {//隐藏密码
                    isShow = false;
                    mIvShowPassword.setImageResource(R.drawable.icon_denglu_yanjing);
                    mEtPassword.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                } else {//显示密码
                    isShow = true;
                    mIvShowPassword.setImageResource(R.drawable.icon_denglu_yanjing_s);
                    mEtPassword.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                }
                mEtPassword.setSelection(mEtPassword.length());
                break;
            case R.id.tv_login://登录
                judgeLoginCondition();

                break;
            case R.id.tv_forget_password://忘记密码
                startActivity(ForgetPasswordActivity.class);
                break;
        }
    }

    /**
     * 设置更多用户的选择列表
     */
    private void getMoreUser() {
        if ((List<RecordUserInformationModel>) mSPUtils.getObject("more_user") != null) {
            mMoreUserList.clear();
            Log.d("", "getMoreUser: " + (List<RecordUserInformationModel>) mSPUtils.getObject("more_user"));
            mMoreUserList.addAll((List<RecordUserInformationModel>) mSPUtils.getObject("more_user"));
        }
        mIvMoreUser.setVisibility(mMoreUserList.size() > 0 ? View.VISIBLE : View.GONE);
        mRvMoreUser.setLayoutManager(new LinearLayoutManager(this));
        mMoreUserAdapter = new MoreUserAdapter(mMoreUserList);
        mRvMoreUser.setAdapter(mMoreUserAdapter);
        mMoreUserAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                mEtEnterpriseCode.setText(mMoreUserAdapter.getData().get(position).getCompanyId());
                mEtUser.setText(mMoreUserAdapter.getData().get(position).getLoginName());
                mEtPassword.setText(mMoreUserAdapter.getData().get(position).getLoginPassword());
                isArrow = false;
                mIvMoreUser.setImageResource(R.drawable.icon_denglu_xiaarrow);
                mRvMoreUser.setVisibility(View.GONE);
                mLlBottom.setVisibility(View.VISIBLE);
            }
        });
        mMoreUserAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                //循环判断删除的是否与输入框中的值相同，相同则将输入框中的值置为空
                for (RecordUserInformationModel r : mMoreUserAdapter.getData()) {
                    if (r.getLoginName().equals(mEtUser.getText().toString().trim())) {
                        mEtEnterpriseCode.setText("");
                        mEtUser.setText("");
                        mEtPassword.setText("");
                        mSPUtils.remove("enterprise_code");
                        mSPUtils.remove("user");
                        mSPUtils.remove("password");
                    }
                }
                mMoreUserAdapter.getData().remove(position);
                mSPUtils.put("more_user", mMoreUserAdapter.getData());
                adapter.notifyItemRemoved(position);
                //判断是否删除最后一个值  是则隐藏该布局
                if (mMoreUserAdapter.getData().size() == 0) {
                    isArrow = false;
                    mCbRememberPassword.setChecked(false);
                    mSPUtils.put("remember_password", mCbRememberPassword.isChecked());
                    mIvMoreUser.setImageResource(R.drawable.icon_denglu_xiaarrow);
                    mRvMoreUser.setVisibility(View.GONE);
                    mIvMoreUser.setVisibility(View.GONE);
                    mLlBottom.setVisibility(View.VISIBLE);
                }
            }
        });
    }

    /**
     * 登录作判断
     */
    private void judgeLoginCondition() {
        mCompanyId = mEtEnterpriseCode.getText().toString().trim();
        mLoginName = mEtUser.getText().toString().trim();
        mLoginPassword = mEtPassword.getText().toString().trim();
        if (TextUtils.isEmpty(mCompanyId)) {
            showShortToast("企业号不能为空！");
            return;
        }
        if (TextUtils.isEmpty(mLoginName)) {
            showShortToast("账号不能为空！");
            return;
        }
        if (TextUtils.isEmpty(mLoginPassword)) {
            showShortToast("密码不能为空！");
            return;
        }
        loginHttp();
    }


    /**
     * 联网登录
     */
    private void loginHttp() {
        mParams = new HashMap<>();
        mParams.put("companyId", mCompanyId);
        mParams.put("loginName", mLoginName);
        mParams.put("loginPassword", mLoginPassword);
        mParams.put("token", "");
        mNetProtocol.login(this, mParams, "登录中...", new HttpUtils.IHttpResult() {
            @Override
            public void onSuccess(BaseBean baseBean) {
                LoginModel loginModel = (LoginModel) baseBean.getData();
                if (loginModel.isIsLogin()) {
                    RecordUserInformationModel recordUserInformationModel = new RecordUserInformationModel();
                    mSPUtils.put("enterprise_code", EncodeUtils.base64Encode2String(mCompanyId.getBytes()));
                    mSPUtils.put("user", EncodeUtils.base64Encode2String(mLoginName.getBytes()));
                    mSPUtils.put("remember_password", mCbRememberPassword.isChecked());
                    if (mCbRememberPassword.isChecked()) {//是否记住密码
                        mSPUtils.put("password", EncodeUtils.base64Encode2String(mLoginPassword.getBytes()));

                        //记录用户账号信息
                        recordUserInformationModel.setCompanyId(mCompanyId);
                        recordUserInformationModel.setLoginName(mLoginName);
                        recordUserInformationModel.setLoginPassword(mLoginPassword);
                        if (!mMoreUserList.toString().contains(mLoginName)) {//新账号则添加到该集合
                            mMoreUserList.add(recordUserInformationModel);
                        } else {//否则循环遍历 找到该账号 替换账号新数据
                            for (int i = 0; i < mMoreUserList.size(); i++) {
                                if (mMoreUserList.get(i).getLoginName().equals(mLoginName)) {
                                    mMoreUserList.set(i, recordUserInformationModel);
                                }
                            }
                        }
                    } else { //判断同上  --  不记住密码的情况
                        mSPUtils.put("password", "");

                        recordUserInformationModel.setCompanyId("");
                        recordUserInformationModel.setLoginName(mLoginName);
                        recordUserInformationModel.setLoginPassword("");
                        if (!mMoreUserList.toString().contains(mLoginName)) {
                            mMoreUserList.add(recordUserInformationModel);
                        }
                    }
                    //保存用户账号信息
                    mSPUtils.put("more_user", mMoreUserList);
                    //保存userCode
                    mSPUtils.put("user_code", loginModel.getUserCode());
                    //保存token
                    mSPUtils.put("token", loginModel.getToken());

                    if ((StoreModel) mSPUtils.getObject(loginModel.getUserCode() + "_store") == null) {
                        mBundle = new Bundle();
                        mBundle.putString("username", loginModel.getFullName());
                        startActivityAndFinish(HomeActivity.class, mBundle);
                    } else {
                        selectStore(loginModel.getToken(), (StoreModel) mSPUtils.getObject(loginModel.getUserCode() +
                                "_store"));
                    }
                }
            }

            @Override
            public void onFail(BaseBean baseBean) {
                showShortToast(baseBean.getMessage());
            }
        });
    }

    /**
     * 默认选择该账号退出前选择的门店
     *
     * @param token
     * @param storeModel
     */
    private void selectStore(String token, final StoreModel storeModel) {
        mParams = new HashMap<>();
        mParams.put("companyId", mCompanyId);
        mParams.put("loginName", mLoginName);
        mParams.put("loginPassword", mLoginPassword);
        mParams.put("storeId", storeModel.getStoreId());
        mParams.put("token", token);
        mNetProtocol.login(this, mParams, "登录中...", new HttpUtils.IHttpResult() {
            @Override
            public void onSuccess(BaseBean baseBean) {
                LoginModel loginModel = (LoginModel) baseBean.getData();
                mBundle = new Bundle();
                mBundle.putString("username", loginModel.getFullName());
                startActivityAndFinish(HomeActivity.class, mBundle);
            }

            @Override
            public void onFail(BaseBean baseBean) {

            }
        });
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[]
            grantResults) {
        switch (requestCode) {
            case CustomCodeUtils.REQUEST_CAMERA:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    showShortToast("授权成功！");
                } else {
                    showShortToast("获取相机权限失败，请在使用之前在系统设置中授权。");
                }
                break;
            default:
        }
    }

    @OnClick(R.id.iv_bg)
    public void onViewClicked() {
        /**
         * 实现双击方法
         * src 拷贝的源数组
         * srcPos 从源数组的那个位置开始拷贝.
         * dst 目标数组
         * dstPos 从目标数组的那个位子开始写数据
         * length 拷贝的元素的个数
         */
        System.arraycopy(mHits, 1, mHits, 0, mHits.length - 1);
        //实现左移，然后最后一个位置更新距离开机的时间，如果最后一个时间和最开始时间小于DURATION，即连续10次点击
        mHits[mHits.length - 1] = SystemClock.uptimeMillis();
        if (mHits[0] >= (SystemClock.uptimeMillis() - DURATION)) {
            View view = View.inflate(LoginActivity.this, R.layout.dialog_test_view, null);
            ListView lvTestUrl = view.findViewById(R.id.lv_test_url);
            ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, URl_NAME);
            lvTestUrl.setAdapter(arrayAdapter);
            final Dialog dialog = DialogUtil.getDialog(LoginActivity.this, view);
            lvTestUrl.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                    mTvTest.setText(URl_NAME[i].equals("正式") ? "" : "test");
                    FinalUrl.setURL(URL_LIST[i]);
                    dialog.dismiss();
                }
            });
        }
    }
}
